package com.hardson.toolkit.swing.print;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

import lombok.Getter;

/**
 *
 * 使用了原始的分页方式去渲染JTextArea，提供了打印预览机制。
 *
 * <p>
 *
 * 事实上，我们还可以通过其他方式打印JTextArea：
 *
 * <ol>
 *
 * <li>{@code Component.print(Graphics g);} or
 *
 * {@code Component.printAll(Graphics g);}</li>
 *
 * <li>{@code Component.paint(Graphics g);} or
 *
 * {@code Component.paintAll(Graphics g);} whose rending may be slightly
 *
 * different to the previous method (for example, <code>JFrame</code>)</li>
 *
 * <li>{@code JTable.print();} or {@code JTextComponent.print();} provide
 *
 * especially powerful and convenient printing mechanism</li>
 *
 * </ol>
 *
 *
 *
 * @author Gaowen
 *
 */

public class Preview extends JPanel implements Printable {

	private static final long serialVersionUID = 4797002827940419724L;

	private JTextArea textAreaToPrint;

	@Getter
	private PrinterJob job;

	@Getter
	private int[] pageBreaks;// array of page break line positions

	private String[] textLines;

	@Getter
	private PreviewHeader header;

	private JFrame frame;

	public Preview(final JFrame frame) {
		super(new BorderLayout());
		this.frame = frame;
		this.textAreaToPrint = new JTextArea(50, 20);
		for (int i = 1; i <= 50; i++) {
			this.textAreaToPrint.append("Line " + i + "\n");
		}
		JScrollPane scrollPane = new JScrollPane(this.textAreaToPrint);
		scrollPane.setPreferredSize(new Dimension(250, 200));
		this.add(scrollPane, BorderLayout.CENTER);
		JButton printButton = new JButton("Print This TextArea");
		printButton.setName("printButton");
		printButton.addActionListener((e) -> this.printTextArea());
		JButton printPreviewButton = new JButton("Print Preview");
		printPreviewButton.setName("printPreviewButton");
		printPreviewButton.addActionListener((e) -> this.printPreview());
		JPanel buttonGroup = new JPanel(new GridLayout(2, 1));
		buttonGroup.add(printButton);
		buttonGroup.add(printPreviewButton);
		this.add(buttonGroup, BorderLayout.SOUTH);
		/* Initialize PrinterJob */
		this.initPrinterJob();

	}

	public static void main(final String[] args) {
		int dpi = Toolkit.getDefaultToolkit().getScreenResolution();
		System.out.println("dpi=" + dpi);
		EventQueue.invokeLater(() -> createAndShowGUI());
	}

	private static void createAndShowGUI() {
		JFrame frame = new JFrame("Print UI Example");
		frame.setContentPane(new Preview(frame));
		frame.pack();
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

	private void initTextLines() {
		Document doc = this.textAreaToPrint.getDocument();
		try {
			String text = doc.getText(0, doc.getLength());
			this.textLines = text.split("\n");
		} catch (BadLocationException e) {
			e.printStackTrace();
		}
	}

	private void initPrinterJob() {
		this.job = PrinterJob.getPrinterJob();
		this.job.setJobName("Print TextArea");// 出现在系统打印任务列表
		this.job.setPrintable(this);
	}

	@Override
	public int print(final Graphics graphics, final PageFormat pageFormat, final int pageIndex)
			throws PrinterException {
		/*
		 * It is safe to use a copy of this graphics as this will not involve
		 * changes to it.
		 */
		Graphics2D g2 = (Graphics2D) graphics.create();
		/* Calculate "pageBreaks" */
		Font font = new Font("Serif", Font.PLAIN, 12);
		FontMetrics metrics = g2.getFontMetrics(font);
		int lineHeight = metrics.getHeight();
		if (this.pageBreaks == null) {
			this.initTextLines();
			int linesPerPage = (int) (pageFormat.getImageableHeight() / lineHeight);
			int numBreaks = (this.textLines.length - 1) / linesPerPage;
			this.pageBreaks = new int[numBreaks];
			for (int b = 0; b < numBreaks; b++) {
				this.pageBreaks[b] = (b + 1) * linesPerPage;
			}
		}

		/* Condition to exit printing */
		if (pageIndex > this.pageBreaks.length) {
			return NO_SUCH_PAGE;
		}

		/* (0,0) is outside the imageable area, translate to avoid clipping */
		g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
		/* Draw each line that is on this page */
		int y = 0;
		int start = (pageIndex == 0) ? 0 : this.pageBreaks[pageIndex - 1];
		int end = (pageIndex == this.pageBreaks.length) ? this.textLines.length
				: this.pageBreaks[pageIndex];
		for (int line = start; line < end; line++) {
			y += lineHeight;
			g2.drawString(this.textLines[line], 0, y);
		}

		/* dispose of the graphics copy */
		g2.dispose();
		/* Tell the caller that this page is part of the printed document */
		return PAGE_EXISTS;
	}

	private void printTextArea() {
		this.pageBreaks = null;// reset pagination
		boolean ok = this.job.printDialog();
		if (ok) {
			try {
				this.job.print();
			} catch (PrinterException ex) {
				/* The job did not successfully complete */
				ex.printStackTrace();
			}
		}
	}

	private void printPreview() {
		this.pageBreaks = null;// reset pagination
		this.showPreviewDialog();
	}

	private void showPreviewDialog() {
		JDialog previewDialog = new JDialog(this.frame, "Print Preview Dialog", true);
		JPanel contentPane = new JPanel(new BorderLayout());
		PreviewArea previewArea = new PreviewArea(this);
		previewArea.addMouseListener(new PreviewAreaMouseAdapter(previewArea));
		JScrollPane scrollPane = new JScrollPane(previewArea);
		contentPane.add(scrollPane, BorderLayout.CENTER);
		this.header = new PreviewHeader(this, previewArea);
		contentPane.add(this.header, BorderLayout.NORTH);
		previewDialog.setContentPane(contentPane);
		previewDialog.setSize(1350, 1000);
		previewDialog.setLocationRelativeTo(this.frame);
		previewDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		previewDialog.setVisible(true);
	}

	private class PreviewAreaMouseAdapter extends MouseAdapter {
		private PreviewArea previewArea;

		private PreviewAreaMouseAdapter(final PreviewArea previewArea) {
			this.previewArea = previewArea;
		}

		@Override
		public void mouseClicked(final MouseEvent e) {
			int currentIndex = this.previewArea.getPageIndex();
			if (e.getButton() == MouseEvent.BUTTON1) {
				/* next page */
				if (currentIndex < Preview.this.pageBreaks.length) {
					this.previewArea.setPageIndex(currentIndex + 1);
					this.previewArea.repaint();
				}
			} else if (e.getButton() == MouseEvent.BUTTON3) {
				/* previous page */
				if (currentIndex > 0) {
					this.previewArea.setPageIndex(currentIndex - 1);
					this.previewArea.repaint();
				}
			}
		}
	}
}
